Ext.onReady(function(){ 

Ext.QuickTips.init();
Ext.form.Field.prototype.msgTarget = 'under';

// checkColumn
Ext.grid.CheckColumn = function(config){  
    Ext.apply(this, config);  
    if (!this.id) {  
        this.id = Ext.id();  
    }  
    this.renderer = this.renderer.createDelegate(this);  
};  
  
Ext.grid.CheckColumn.prototype = {  
    init: function(grid){  
        this.grid = grid;  
        this.grid.on('render', function(){  
            var view = this.grid.getView();  
            view.mainBody.on('mousedown', this.onMouseDown, this);  
        }, this);  
    },  
    onMouseDown: function(e, t){  
        if (t.id == this.id) {  
            e.stopEvent();  
            var index = this.grid.getView().findRowIndex(t);//行号  
            var cindex = this.grid.getView().findCellIndex(t);//列号 
            var record = this.grid.store.getAt(index);//行记录  
            var field = this.grid.colModel.getDataIndex(cindex);//列名  
            var value = !record.data[this.dataIndex];//点击后，获得当前checkbox值的相反值  
            var store = this.grid.store;
            record.set(this.dataIndex, value);//设定checkbox被选择时候的值  
            //事件的参数  
            var e = {  
               grid: this.grid,  
               record: record,  
               field: field,   
               originalValue: record.data[this.dataIndex],  
               value: !record.data[this.dataIndex],  
               row: index,  
               store: store,
               column: cindex  
           };  
  
            //向上查询descripe2相同，查4位
            var upFlag = true; //向上标记，为1时终止
            var downFlag = true; // 向下标记，为1时终止
            var result = new Array(4); //最多能找到4个
            var count = 0; //总计
            var i = 0; //向上
            var j = 0; //向下
            //alert(index);
            
            //先向上查询
           	while(upFlag && index - i >= 0){
           		if(store.getAt(index-i).get('describe3') === store.getAt(index).get('describe3')){
           			result[count++] = index-i;
           		}else{
           			upFlag = false;
           		}
           		//alert("i:" +i);
           		i++;
           	}
           	
            //向下查询
           	//alert("total: "+store.getCount());
           	while(downFlag && index + j < store.getCount()){
           		if(store.getAt(index+j).get('describe3') === store.getAt(index).get('describe3')){
           			result[count++] = index+j;
           		}else{
           			downFlag = false;
           		}
           		//alert("j:" +j);
           		j++;
           	}
           	
           	//遍历result， 将结果中的行设置value
           	//value为false的时候不处理，否则其他行会被置为true
           	if(value){
           		for(var k=0; k<count && result[k]!==null ;k++){
           			this.grid.store.getAt(result[k]).set(field,!value);
           		} 
           	}
           	this.grid.store.getAt(index).set(field,value);
           	
           	
        }  
    },  
    renderer: function(v, p, record){  
        p.css += ' x-grid3-check-col-td';  
        return '<div id="' + this.id + '" class="x-grid3-check-col' + (v ? '-on' : '') + '">&#160;</div>';  
    }  
};


var checkColumn = new Ext.grid.CheckColumn({  
                   header: "选择",  
                   dataIndex: 'checkSelect',  
                   width: 30  
        });  


function getBodyWidth(){  
    return document.body.clientWidth-15;  
}  
  

var _bodyWidth = getBodyWidth();  
var _columns = 5;  
var _perWidth = _bodyWidth/_columns;  
    
var config={
    title:"提示",
    width:240,
    msg:'<div align="center">操作成功！</div>',
    closable:false,
    buttons:{cancel:'取消',yes:'添加新的大类',no:'继续添加子类'},
    fn: function(btn){
    	//alert('单击的按钮id是：'+btn);
    	if(btn == 'no'){
    		var nowDescribe1 = Ext.getCmp('describe1').getValue();
    		addForm.form.reset();
    		Ext.getCmp('describe1').setValue(nowDescribe1);
    		grid.store.reload(); 
    	}
    	else if(btn == 'yes'){
    		addForm.form.reset();
    		grid.store.reload(); 
    	}
    	
    }
    //icon:Ext.MessageBox.Question
}



function func_submit_onclick(){  
    if(addForm.form.isValid()){
		addForm.form.doAction('submit', { 
			url : 'model/addAdjustment.do',
			method : 'POST',
			success : function() {
				var msgbox = Ext.MessageBox.show(config); 
				msgbox.getDialog().moveTo(100, 100); 
				//setPosition(event.x - 300 ,event.y + 100); 
				//Ext.Msg.alert("提示", "操作成功！");
				grid.store.reload(); 
			},
			failure : function() {
				Ext.MessageBox.alert("请求异常！");
			}
		});
	}    
}  

var fm = Ext.form;

//Gridpanel
var cm=new Ext.grid.ColumnModel([
{header:'流水号',dataIndex:'serialNo',hidden:true,
editor: new fm.TextField({allowBlank: false,editable:false,readOnly:true})
} ,
{header:'特征项信息',
	sortable: true, renderer: function (value, meta, record, rowIndex, colIndex, store) {
                    var first = !rowIndex || value !== store.getAt(rowIndex - 1).get('describe1'),
                        last = rowIndex >= store.getCount() - 1 || value !== store.getAt(rowIndex + 1).get('describe1');
                    meta.css += 'row-span' + (first ? ' row-span-first' : '') +  (last ? ' row-span-last' : '');
                    if (first) {
                        var i = rowIndex + 1;
                        while (i < store.getCount() && value === store.getAt(i).get('describe1')) {
                            i++;
                        }
                        var rowHeight = 20, padding = 6,
                            height = (rowHeight * (i - rowIndex) - padding) + 'px';
                        meta.attr = 'style="height:' + height + ';line-height:' + height + ';"';
                    }
                    return first ? value : '';
                }, 
	dataIndex:'describe1',
	width:50
    },
{header:'特征项说明',
	sortable: true, renderer: function (value, meta, record, rowIndex, colIndex, store) {
                    var first = !rowIndex || value !== store.getAt(rowIndex - 1).get('describe3'),
                        last = rowIndex >= store.getCount() - 1 || value !== store.getAt(rowIndex + 1).get('describe3');
                    meta.css += 'row-span' + (first ? ' row-span-first' : '') +  (last ? ' row-span-last' : '');
                    if (first) {
                        var i = rowIndex + 1;
                        while (i < store.getCount() && value === store.getAt(i).get('describe3')) {
                            i++;
                        }
                        //alert("i: "+i+" rowIndex:"+rowIndex);
                        var rowHeight = 20, padding = 6,
                            height = (rowHeight * (i - rowIndex) - padding) + 'px';
                        meta.attr = 'style="height:' + height + ';white-space:normal;"';
                    }
                    return first ? value : '';
                },
dataIndex:'describe3',
width:100
}, 

checkColumn ,
{header:'描述',
dataIndex:'itemDescribe',
width:80,
renderer: function (value, metadata, record){
	metadata.attr = 'style="white-space:normal;"'; 
	return value; 
},
},

]); 

var ds = new Ext.data.Store({ 
proxy:new Ext.data.HttpProxy({
url:'rating/listModelItems.do?dataFlag=3',
method:'POST'
}), 
reader:new Ext.data.JsonReader({ 
totalProperty:'total',  
root:'resultData'},[
{name:'serialNo'},
{name:'describe1'}, 
{name:'describe2'},  
{name:'describe3'},
{name:'checkSelect'},
{name:'itemDescribe'},
{name:'itemValue'},
{name:'itemWeight'}
]) 
}); 
ds.load(); 


var grid=new Ext.grid.EditorGridPanel({ 
id:'myCustomers',
stripeRows:true,//斑马线效果
title:'<div align="center">特征项</div>', 
height:600, 
cm:cm,
store: ds, 
clicksToEdit: 1,
columnLines:true, 
plugins:checkColumn,
cls: 'grid-row-span',
loadMask: { msg: "加载中..." }, 
viewConfig: {   
                            forceFit:true   
            },  

bbar: [{text:'<b>提交</b>', id:'submit', height:'30',width:'1000',handler:submitM},'-']
                      
});

function submitM(){
	var mr=ds.getModifiedRecords();//获取所有更新过的记录  
     var recordCount=ds.getCount();//获取数据集中记录的数量  
     if(mr.length==0){  // 确认修改记录数量  
       alert("没有修改数据！");  
       return false;  
     }  
       
     var recordModStr="[";//这里以josn方式保存  
     for(var i=0;i<mr.length;i++){ 
     recordModStr+=Ext.util.JSON.encode(mr[i].data);
    
      //recordModStr+="{serialNo:"+"\""+mr[i].data["serialNo"]+"\""+",pdlevel:"+"\""+mr[i].data["pdlevel"]+"\""+",pdvalue:"+mr[i].data["pdvalue"]+"}";  
       
     	if(i<mr.length-1)  
      	recordModStr+=","; 
    } 
     recordModStr+="]";
    
     //alert(recordModStr);
     Ext.Ajax.request({
		url:'rating/addAdjValue.do',
		params : { newRecord: recordModStr},
		method:'POST',
		success:function(){
			Ext.MessageBox.alert("提示","提交成功！");
			grid.store.reload(); 
		},failure:function(){
			Ext.MessageBox.alert("提示", "操作失败！"); 
		}
	});  
}

var panel =  new Ext.Panel({
renderTo:"panel",
items:[grid]
});

var accessURL = document.getElementById("accessURL").innerHTML;
var phaseStat = document.getElementById("phaseStat").innerHTML;
if((phaseStat != '01' && phaseStat != '00'&& phaseStat != '07' )  || accessURL.indexOf("/rating/CustomerRating_IndSecondPD.jsp") > 0 || accessURL.indexOf("/rating/CustomerRating_IndConfirmPD.jsp") > 0 || accessURL.indexOf("/rating/CustomerRating_IndFirstVerifyPD.jsp") > 0){
	Ext.getCmp('submit').hide()
}

}); 